/**
 * @author zhouheng
 * @date 2022年03月07日 21:42
 */

package com.gulimall.search.gulimallsearch.thread;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import jdk.nashorn.api.scripting.ScriptUtils;

public class ThreadTest {

    // CompletableFuture 异步线程任务 测试

    public static void main(String[] args) {
        // runable / runable,Executor
//        CompletableFuture completableFuture = CompletableFuture.runAsync(new Runnable() {
//            @Override
//            public void run() {
//                try {
//                    Thread.sleep(3_000);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//                System.out.println("我非常耗时对不对，不好意思哈。。。");
//            }
//        }).whenComplete((a,b) -> {
//
//        });
//
//
//        try {
//            System.out.println("等待执行");
//            completableFuture.get();
//            System.out.println("结束了，安静了");
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        } catch (ExecutionException e) {
//            e.printStackTrace();
//        }

        ExecutorService executorService = Executors.newSingleThreadExecutor();
        System.out.println("begin....");
        CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> {
            System.out.println("耗时的计算开始啦，但是我不阻塞哈");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            int i = 2;
            int val = 10 / i;

            return val;
        }, executorService).handle((res, thr) -> {
            if (res == null) {
                // 有异常
                return 0;
            } else if (thr != null){
                return res * 2;
            }

            return 0;
        });

        try {
            Integer integer = completableFuture.get();
            System.out.println("业务返回结果："+ integer);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        System.out.println("end....");

    }
}
